package com.sjy.framework.interceptor;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.sjy.common.constant.UserContext;
import com.sjy.common.entity.SecuryUserDetail;
import com.sjy.common.result.BaseResponse;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.TokenUtil;
 
public class TokenInterceptor extends HandlerInterceptorAdapter {
 
	private TokenUtil tokenUtil;
 
	public TokenInterceptor(TokenUtil tokenUtil) {
		this.tokenUtil = tokenUtil;
	}
 
	private Logger logger = LoggerFactory.getLogger(this.getClass());
 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
//		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//		response.setHeader("Access-Control-Allow-Methods", "*");
//		response.setHeader("Access-Control-Max-Age", "3600");
//		response.setHeader("Access-Control-Allow-Credentials", "true"); 
		String uri = request.getRequestURI();
		if(uri.contains("/api/")&&uri.contains("/noToken/")) {
			return true;
		}
		String token = request.getHeader("token");
		if(StringUtils.isBlank(token)) {
			token = request.getParameter("token");
		}
		// verify token
		tokenUtil.verifyToken(token);

		// result
		if (tokenUtil.result) {
			SecuryUserDetail securyUserDetail = tokenUtil.parseToken(token);
			UserContext.setUserSession(securyUserDetail);
//			//预警平台用户，bu/api/issue/info 部分接口他们才有权限
//			if(securyUserDetail.getUserType()==-1&&!uri.contains("/api/issue/info")) {
//				returnMsg(response,BaseResponse.generateBadResponseEntity(403,"无权访问接口!", tokenUtil.message));
//				return false;
//			}
			return true;
		} else {
			
//			if(uri.contains("/api/")) {
//				return true;
//			}
			//通用免登陆接口
			
			returnMsg(response,BaseResponse.generateBadResponseEntity(403,"请重新登录!", tokenUtil.message));
			return false;
		}
 
	}
	
	private void returnMsg(HttpServletResponse response,ResponseEntity dto) {
		 try {
			response.setContentType("application/json;charset=utf-8");
			   	response.getWriter().print( JSON.toJSONString(dto.getBody()));
			   	response.getWriter().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
}
